package my;

import javax.swing.*;
import java.awt.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.java_websocket.WebSocket;

public class MyFrame extends JFrame {
    private TCPClient tcpClient;
    private UDPClient udpClient;
    private String currentServ = "tcp";
    private WebsocketClient client;

    JLabel l1 = new JLabel("服务器IP：");
    JTextField t1 = new JTextField(12);
    JLabel l2 = new JLabel("端口");
    JTextField t2 = new JTextField(4);
    JButton b1 = new JButton("TCP连接");
    JButton b2 = new JButton("UDP连接");
    JButton b3 = new JButton("Websocket连接");
    JButton b4 = new JButton("关于");
    JButton cleanText = new JButton("清空信息");

    JLabel d1 = new JLabel("Text：");
    JLabel d2 = new JLabel("Text：");
    JLabel d3 = new JLabel("Text：");
    JLabel d4 = new JLabel("Text：");
    JTextField text1 = new JTextField(50);
    JTextField text2 = new JTextField(50);
    JTextField text3 = new JTextField(50);
    JTextField text4 = new JTextField(50);
    JButton button1 = new JButton("Send");
    JButton button2 = new JButton("Send");
    JButton button3 = new JButton("Send");
    JButton button4 = new JButton("Send");
    JButton closeConnection = new JButton("关闭连接");

    static JTextArea textArea = new JTextArea(null, 10, 60);

    public MyFrame(String title) {
        super(title);
        //初始化内容窗体
        Container contentPane = getContentPane();
        //使用边界布局
        contentPane.setLayout(new FlowLayout());
        t1.setText("121.40.165.18");
        t2.setText("8800");
        text1.setPreferredSize(new Dimension(0, 27));
        text2.setPreferredSize(new Dimension(0, 27));
        text3.setPreferredSize(new Dimension(0, 27));
        text4.setPreferredSize(new Dimension(0, 27));
        contentPane.add(l1);
        contentPane.add(t1);
        contentPane.add(l2);
        contentPane.add(t2);
        contentPane.add(b1);
        contentPane.add(b2);
        contentPane.add(b3);
        contentPane.add(b4);
        contentPane.add(d1);
        contentPane.add(text1);
        contentPane.add(button1);
        contentPane.add(d2);
        contentPane.add(text2);
        contentPane.add(button2);
        contentPane.add(d3);
        contentPane.add(text3);
        contentPane.add(button3);
        contentPane.add(d4);
        contentPane.add(text4);
        contentPane.add(button4);
        contentPane.add(cleanText);
        contentPane.add(closeConnection);

        // 创建滚动面板, 指定滚动显示的视图组件(textArea), 垂直滚动条一直显示, 水平滚动条从不显示
        JScrollPane scrollPane = new JScrollPane(
                textArea,
                ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
        );
        contentPane.add(scrollPane);

        button1.addActionListener((e)->{sendTcpMessage(1);});
        button2.addActionListener((e)->{sendTcpMessage(2);});
        button3.addActionListener((e)->{sendTcpMessage(3);});
        button4.addActionListener((e)->{sendTcpMessage(4);});
        b1.addActionListener((e)->{
            //与TCP服务器建立连接
            this.currentServ = "tcp";
            String res = getInput();
            String[] arr = res.split(",");
            String ip = arr[0];
            int port = Integer.parseInt(arr[1]);
            this.tcpClient = new TCPClient(ip, port) {
                @Override
                protected void onDataReceive(byte[] bytes, int size) {
                    String content = "TCPServer:" + new String(bytes, 0, size);
                    appendText(content);
                }
            };
            tcpClient.connect();//连接TCPServer
            if (this.tcpClient.isConnected()) {
                appendText(ip + " was connected successful!");
            }
        });
        b2.addActionListener((e)->{
            //与UDP服务器建立连接
            this.currentServ = "udp";
            String res = getInput();
            String[] arr = res.split(",");
            String ip = arr[0];
            int port = Integer.parseInt(arr[1]);
            this.udpClient = new UDPClient(ip,port){
                @Override
                protected void onDataReceive(byte[] bytes, int size) {
                    String content = "UDPServer:" + new String(bytes, 0, size);
                    appendText(content);
                }
            };
            udpClient.connect();//连接UDPServer
            if (this.udpClient.isConnected()) {
                appendText(ip + " was connected successful!");
            }
        });
        b3.addActionListener((e)-> {
            //与Websocket服务器建立连接
            this.currentServ = "websocket";
            String res = getInput();
            String[] arr = res.split(",");
            String url = null;

            try {
                client = new WebsocketClient(new URI("ws://" + arr[0] + ":" + arr[1])) {};
            } catch (URISyntaxException eu) {
                MyFrame.appendText(eu.getMessage());
            }
            client.connect();
        });
        b4.addActionListener((e)->{JOptionPane.showMessageDialog(null, "Author:Leo\nwww.changliang.top");});
        cleanText.addActionListener((e)->{textArea.setText("");});
        closeConnection.addActionListener((e)->{
            if (this.currentServ == "tcp") {
                try {
                    this.tcpClient.close();//关闭TCP连接
                } catch (Exception ex) {
                    appendText("TCP连接关闭失败，或者尚未连接到TCPServer");
                }
            }
            if (this.currentServ == "udp") {
                try {
                    this.udpClient.close();//关闭UDP连接
                } catch (Exception ex) {
                    appendText("UDP连接关闭失败，或者尚未连接到UDPServer");
                }
            }
            if (this.currentServ == "websocket") {
                try {
                    this.client.close();
                } catch (Exception ex) {
                    appendText("Websocket连接关闭失败，或者尚未连接到Websocket");
                }
            }
        });
    }

    //向TCPServer发送消息
    private void sendTcpMessage(int index) {
        String clientMessage = null;
        //if (this.tcpClient.isConnected() || this.udpClient.isConnected()){
            //获取用户输入
            switch (index) {
                case 1 -> clientMessage = text1.getText();
                case 2 -> clientMessage = text2.getText();
                case 3 -> clientMessage = text3.getText();
                case 4 -> clientMessage = text4.getText();
            }
            if ("".equals(clientMessage)) {
                JOptionPane.showMessageDialog(null, "不能留空");
                return;
            }
            System.out.println(clientMessage);
            String outContent = "";
            //发送数据
            if (this.currentServ == "tcp") {
                outContent = "TCPClient：" + clientMessage;
                this.tcpClient.send(outContent.getBytes());
            } else if (this.currentServ == "udp") {
                outContent = "UDPClient：" + clientMessage;
                this.udpClient.send(outContent.getBytes());
            } else {
                outContent = "WebsocketClient：" + clientMessage;
                this.client.send(outContent);
            }
            appendText(outContent);
        //}
    }

    //向textarea追加信息
    static void appendText(String info) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                SimpleDateFormat ft = new SimpleDateFormat("hh:mm:ss");
                if (info != null) {
                    textArea.append("[" + ft.format(new Date()) + "]" +info + "\n");
                }
            }
        });
    }

    //接收用户输入ip和port
    private String getInput() {
        //获取ip、端口
        String ip = t1.getText();
        if ("".equals(ip)) {
            JOptionPane.showMessageDialog(null, "IP必需输入");
            return null;
        }
        String port = t2.getText();
        if ("".equals(port)) {
            JOptionPane.showMessageDialog(null, "Port必需输入");
            return null;
        }
        return ip + "," + port;
    }


}